package com.meng.message.service.impl.user;


import com.meng.message.controller.login.CaptchaController;
import com.meng.message.domain.user.MiniUserDetails;
import com.meng.message.domain.vo.SysUserVO;
import com.meng.message.service.auth.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: Xu Meng
 * @program: minions-cloud
 * @create: 2021-01-27 17:33
 **/
@Slf4j
@Service("myUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String captcha = request.getParameter("captcha");
        String captchaSession = (String) request.getSession().getAttribute(CaptchaController.KEY_CAPTCHA);
        if (! captcha.equalsIgnoreCase(captchaSession)){
            throw new RuntimeException("验证码错误");
        }
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        SysUserVO sysUser = sysUserService.getUserVoByLoginName(username);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        //获取该用户所拥有的权限
        List<String> roleIds = sysUserService.findUserIdByRolesId(sysUser.getUserId());
        String[] permissionArray = new String[roleIds.size()];
        roleIds.toArray(permissionArray);
        request.getSession().removeAttribute(CaptchaController.KEY_CAPTCHA);
        return new MiniUserDetails("web",sysUser.getUserId(),sysUser.getUsername(),sysUser.getPassword(), AuthorityUtils.createAuthorityList(permissionArray));
//        return User.withUsername(sysUser.getUsername()).password(sysUser.getPassword()).authorities(permissionArray).build();
    }
}
